package com.example.bourse.controller;

import com.example.bourse.core.utils.SseUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ModelAndView;

import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
@Controller
public class SseController {

    @Mapping("/sse-demo")
    public ModelAndView demo() {
        return new ModelAndView("sse-demo.html");
    }

    @Mapping("/sse")
    public void sse(Context ctx) throws IOException {
        // 获取客户端ID
        String clientId = ctx.param("clientId");
        if (!SseUtil.isValidClientId(clientId)) {
            ctx.status(400);
            ctx.output("Invalid clientId");
            return;
        }

        try {
            log.info("SSE connection established for client: {}", clientId);
            // 注册客户端
            if (!SseUtil.registerClient(ctx, clientId)) {
                log.warn("Client {} already exists, closing previous connection", clientId);
                SseUtil.closeClient(clientId);
                return;
            }

            // 持续发送事件
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    if (!SseUtil.isClientConnected(clientId)) {
                        log.info("Client {} disconnected", clientId);
                        break;
                    }

                    String event = "Event at " + LocalDateTime.now();
                    SseUtil.sendEvent(clientId, event);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.info("SSE connection interrupted for client: {}", clientId);
                    Thread.currentThread().interrupt();
                    break;
                } catch (Exception e) {
                    log.error("Error sending event to client {}: {}", clientId, e.getMessage());
                    break;
                }
            }
        } finally {
            try {
                log.info("Closing SSE connection for client: {}", clientId);
                SseUtil.closeClient(clientId);
            } catch (Exception e) {
                log.error("Error closing client {} connection: {}", clientId, e.getMessage());
            }
        }
    }
}
